const csv = require('csvtojson');
const fs = require('fs');
const axios = require('axios')


let bodyTemp_msisdnWriteBusiness = [
    {
        name: "msisdn_write_business_total",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: "DB451"
            },
            {
                labelName: "businessType",
                labelValue: "write"
            },{
                labelName: "year",
                labelValue: ""
            },{
                labelName: "month",
                labelValue: ""
            },{
                labelName: "day",
                labelValue: ""
            }
        ],
        value: 10000
    },

    {
        name: "msisdn_write_business_success_total",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: "DB451"
            },
            {
                labelName: "businessType",
                labelValue: "write"
            },{
                labelName: "year",
                labelValue: ""
            },{
                labelName: "month",
                labelValue: ""
            }, {
                labelName: "day",
                labelValue: ""
            }
        ],
        value: 8000
    }
];

async function readDataFromCsv(filePath) {
    return csv().fromFile(filePath)
        .subscribe(json => {
            return new Promise((resolve, reject) => {
                if (!json) {
                    reject('read csv error')
                } else {
                    resolve(json)
                }
            })
        })
}





function genValueByType(type, sourceValue) {
    let tmp = Math.floor(Math.random() * 3) * 3;
    if (type == 'total') {
        return sourceValue + tmp;
    } 
    return sourceValue - tmp;
}



async function batchSendMetrics(year, month, day) {


    nodeList.filter(x => {
        if (!nodeId || nodeId === '') {
            return true;
        } else {
            return nodeId == x.code;
        }
    }).forEach(nodeInfo => {
        
        let provinceList = nodeInfo.province.split(',');
        provinceList.filter(x => {
            if (!provinceCode || provinceCode == "") {
                return true;
            } else {
                return x == provinceCode;
            }
        }).forEach(p => {
            // console.log(nodeInfo.code, p)
            typeList.forEach(type => {
                let bodyTemp_tmp = JSON.parse(JSON.stringify(bodyTemp_msisdnWriteBusiness))
                let tmpValue = 1;
                for (let i = 0; i < bodyTemp_tmp.length; i++) {
                    let item = bodyTemp_tmp[i]
                    for (let j = 0; j < item.metricsLabels.length; j++) {
                        let y = item.metricsLabels[j];
                        if (y.labelName == "provinceCode") {
                            y.labelValue = p;
                        }
                        if (y.labelName == "nodeId") {
                            y.labelValue = nodeInfo.code;
                        }
                        if (y.labelName == "businessType") {
                            y.labelValue = type;
                        }
                        if (y.labelName == "year") {
                            y.labelValue = year;
                        }
                        if (y.labelName == "month") {
                            y.labelValue = month;
                        }
                        if (y.labelName == "day") {
                            y.labelValue = day;
                        }
                    }
                    if (item.name == 'msisdn_write_business_total') {
                        item.value = genValueByType('total', writeBusinessTotalValue + tmpValue);
                    } else if (item.name == 'msisdn_write_business_success_total') {
                        item.value = genValueByType('success', writeBusinessSuccessValue + tmpValue);
                    } 
                    tmpValue += 2;
                    writeBusinessTotalValue += 50;
                    writeBusinessSuccessValue += 50;
                    if (writeBusinessTotalValue >= 20000) {
                        writeBusinessTotalValue = 16000;
                        writeBusinessSuccessValue = 15990;
                        tmpValue = 1;
                    }
                }
                bodyTemp_tmp.forEach(m => {
                    resultArr.push(m);
                })
            })
        })

    })

    let jsonTmp = JSON.stringify(resultArr)
    // fs.writeFile("msisdnWriteBusiness.txt", jsonTmp, error => {
    //     if (error) throw error;
    // })
    resultArr = new Array();
    writeBusinessTotalValue = 16000;
    writeBusinessSuccessValue = 15990;

    let reportTime = year + month + day + '0100' + '00';

    customConfig = {
        headers: {
            'Content-Type': 'application/json',
            'reportTime': reportTime
        }
    };

    // console.log('jsonTmp: ', jsonTmp)
    const resp = await axios.post(REQ_URL, jsonTmp, customConfig);
    console.log('resp data: ', resp.data)
}


/**
 * config 信息 ==================
 */
let year = "2023";

// order total
let writeBusinessTotalValue = 16000;
let writeBusinessSuccessValue = 15990;



// 填写具体的端节点ID，为空字符串时代表所有端节点ID
// 填写具体的省份编码，为空字符串代表所有的省份
const nodeId = "";
const provinceCode = "";

const REQ_URL = 'http://15.116.20.124:30061/metrics/report';
// const REQ_URL = 'http://localhost:8080/metrics/report';
const typeList = ["write", "roamProvinceWrite", "belongProvinceWrite"]
let resultArr = new Array();


function sleep(time) {
    return new Promise((resolve, reject) => {
        return setTimeout(resolve, time);
    });
}

let nodeList;

let reportMonth = '';
let reportDay = '';

async function batchSendMetricsLoop() {
    console.log('endnode file path: ' + __dirname + '/../node-server-info/en_endnode.csv')
    nodeList = await readDataFromCsv(__dirname + '/../node-server-info/en_endnode.csv');
    let days = [31,28,31,30,31,30,31,31,30,31,30,31] 
    
    ourter:
    for (let i = 0; i < days.length; i++) {
        let month = i.toString().padStart(2, '0');
        reportMonth = month;
        let day = days[i-1];
        for (let j = 1; j <= day; j++) {
            let dayStr = j.toString().padStart(2, '0');
            reportDay = dayStr;
            console.log('exec business month: ' + month + ', day: '  + dayStr)
            await batchSendMetrics(year, month, dayStr);
            // break ourter;
        }
        // break ourter;
    }
    reportMonth = '';
    reportDay = '';
}

async function execReport() {
    if (reportMonth === '' && reportDay === '') {
        batchSendMetricsLoop();
        return 'start...'
    } else {
        return 'business: ' + reportMonth + ", " + reportDay;
    }
}

exports.execReport = execReport;

